<template>
  <div>
    <el-container>
      <el-main>
        <el-col :xs="24">
          <el-card header="领料申请单">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="state"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入领料流水号"
              @select="handleSelect">
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }} </div>
                <span class="addr">{{ item.department }} </span>
                <span class="addr">{{ item.provider }}</span>
              </template>
            </el-autocomplete>
            <el-table
              :data="tableData"
              border
              style="width: 100%">
              <el-table-column
                fixed
                prop="id"
                label="序号"
                width="80">
              </el-table-column>
              <el-table-column
                prop="requisitionId"
                label="领用流水号"
                width="150">
              </el-table-column>
              <el-table-column
                prop="name"
                label="物料名称"
                width="150">
              </el-table-column>
              <el-table-column
                prop="specification"
                label="规格型号"
                width="150">
              </el-table-column>
              <el-table-column
                prop="price"
                label="单价"
                width="150">
              </el-table-column>
              <el-table-column
                prop="dueNum"
                label="数量"
                width="120">
              </el-table-column>
              <el-table-column
                prop="unit"
                label="计量单位"
                width="100">
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="340">
                <template slot="header" slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleInsert(scope.$index, scope.row)"
                  >添加物料</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-main>
    </el-container>
    <!--   添加物料    -->
    <el-dialog title="添加物料" :visible.sync="insFormVisible" :before-close="handleInsClose" width="40%">
      <el-form class="action-form" :model="insForm" label-width="100px">
        <el-form-item label="物资名称">
          <el-autocomplete
            v-model="insForm.materialName"
            :fetch-suggestions="querySearchAsync1"
            placeholder="请输入内容"
            @select="handleSelect1"
          ></el-autocomplete>
        </el-form-item>
        <!-- 实时显示搜索内容-->
        <el-form-item label="申请数量">
          <el-input v-model="insForm.purchaseNum" />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="insForm.specification"/>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="insForm.unit" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="insForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="insFormCancel()">取 消</el-button>
        <el-button type="primary" @click="insFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑弹窗-->
    <el-dialog title="修改物料信息" :visible.sync="editFormVisible" :before-close="handleEditClose" width="40%">
      <el-form class="action-form" :model="updForm" label-width="100px">
        <el-form-item label="流水号">
          <el-input v-model="updForm.requisition_id" :disabled="true" />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="updForm.materialName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="申请数量">
          <el-input v-model="updForm.purchaseNum" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="updForm.price" :disabled="true"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updFormCancel()">取 消</el-button>
        <el-button type="primary" @click="updFormConfirm_good()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { getToken } from '@/utils/auth'
  import { selectById_good, selectAll, selectByReId, editGood, RemoveGood, Select_AccId, insertPurchase } from '@/api/material-delivery/purchase-plan'
  import { selAccountDepart, selectByNot } from '@/api/material-delivery/pur-admin'

  export default {
    data() {
      return {
        tableData: [],
        searchDatas: [],      //初始时搜索框预加载数据
        Data: [],
        GoodsData: [],      //物资信息
        IdData: [],
        editFormVisible: false, // 编辑框是否可见
        insFormVisible: false, //  添加弹出框是否可见
        selFormVisible: false, //  查询物料框是否可见
        loading: true,
        acceptId: '',
        mcurrentPage: 1, //  物料信息表当前页码
        mtotal: 0, //  初始化总条数
        pageSize: 10, //  设置每页的数据条数
        pageTotal: 10, //  初始化总条数
        currentPage: 1, //  申请表当前页码
        pageKey: '', // 分页功能中 table 的key值
        itemKey: '', //  使用key属性强制替换元素，从而触发组件的生命周期钩子或者触发过渡
        materialNameDatas: [], // 记录所有根据名字搜索的内容信息
        timeout: null, //  设置搜索时的响应时间
        account: this.$store.getters.name, // 获取用户信息
        acoDepartName: '', // 获取用户所属部门信息
        requisitionId: '',
        department: '',
        updForm: {
          id: '',
          requisition_id: '',
          materialName: '',
          purchaseNum: '',
          specification: '',
          unit: '',
          actual_num: '',
          price: '',
          tax: '',
          remark: ''
        },
        insForm: {
          materialName: '',
          specification: '',
          unit: '',
          purchaseNum: '',
          remark: '',
          price: ''
        },
        headers: {
          Authorization: getToken()
        },
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        }
      }
    },
    mounted() {
      this.init()
      this.getDepartName()
    },
    methods: {
      init() {
        selectAll().then((response) => {
          this.searchDatas = response.data
        })
        selectByNot().then((response) => {
          this.Data = response.data
        })
      },
      //  添加物料
      handleInsert(index, row) {
        this.insFormVisible = true
      },
      // 关闭 添加物料信息框 之前的操作
      insFormCancel() {
        this.insFormVisible = false
        this.insForm.materialName = ''
        this.insForm.purchaseNum = ''
        this.insForm.partUsed = ''
        this.insForm.remark = ''
      },

      insFormConfirm() {
        if (this.insForm.materialName === '' || this.insForm.purchaseNum === '') {
          this.$message.error('物料名称或申请数量信息不能为空！')
        } else {
          insertPurchase(
            this.insForm.materialName, this.insForm.purchaseNum, this.insForm.specification, this.insForm.unit,
            this.requisitionId, this.insForm.remark, this.insForm.price).then(response => {
            this.$message.success(response.message)
            console.log(this.selectValue)
            selectById_good(this.selectValue).then((response) => {
              this.tableData = response.data
              this.loading = false
              this.itemKey = Math.random()
            })
            this.insFormVisible = false
            this.loading = true
            this.insForm.materialName = ''
            this.insForm.purchaseNum = ''
            this.insForm.partUsed = ''
            this.insForm.remark = ''
          })
        }

      },
      //  关闭 添加窗口 之前的操作
      handleInsClose() {
        this.insFormVisible = false
        this.insForm.materialName = ''
        this.insForm.purchaseNum = ''
        this.insForm.partUsed = ''
        this.insForm.remark = ''
      },
      handleSelect(item) {
        selectById_good(item.value).then((response) => {
          this.selectValue = item.value
          this.tableData = response.data
          this.itemKey = Math.random()
        })
        selectByReId(item.value).then((response) => {
          this.IdData = response.data
          console.log(response.data[0].acceptId)
          Select_AccId(response.data[0].acceptId).then((response) => {
            this.GoodsData = response.data
          })
        })
        this.requisitionId = item.value
      },
      handleSelect1(item) {
        this.insForm.materialName = item.value
        this.insForm.specification = item.specification
        this.insForm.unit = item.unit
        this.insForm.price = item.price
        console.log(item.price)
      },
      querySearchAsync(queryString, cb) {
        var data = this.Data;
        var results = queryString ? data.filter(this.createStateFilter(queryString)) : data;
        var results1 = []
        for (let i = 0; i < results.length; i++) {
          if (results[i].department === this.department) {
            results1.push({
              'value': results[i].requisitionId,
              'department': results[i].department,
              'provider': results[i].provider
            })
          }
        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results1);
        }, 2000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.acceptId.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
        }
      },
      querySearchAsync1(queryString, cb) {
        var goodsData = this.GoodsData;
        var results = queryString ? goodsData.filter(this.createStateFilter(queryString)) : goodsData;
        var results1 = []
        for (let i = 0; i < results.length; i++) {
          results1.push({
            'value': results[i].name,
            'specification': results[i].specification,
            'unit': results[i].unit,
            'price': results[i].price
          })
        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results1);
        }, 2000 * Math.random());
      },
      createStateFilter1(queryString) {
        return (state) => {
          return (state.acceptId.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
        }
      },
      handleEdit(index, row) {
        this.editFormVisible = true

        this.updForm.id = row.id
        this.updForm.requisition_id = row.requisitionId
        this.updForm.materialName = row.name
        this.updForm.specification = row.specification
        this.updForm.unit = row.unit
        this.updForm.purchaseNum = row.dueNum
        this.updForm.price = row.price
        this.updForm.tax = ''
        this.updForm.remark = ''
        this.updForm.actual_num = ''
      },
      updFormCancel() {
        this.editFormVisible = false
        this.updForm.requisition_id = ''
        this.updForm.id = ''
        this.updForm.purchaseNum = ''
        this.updForm.materialName = ''
        this.updForm.specification = ''
        this.updForm.unit = ''
        this.updForm.price = ''
      },
      updFormConfirm_good() {
        this.editFormVisible = false
        editGood(
          this.updForm.id,
          this.updForm.requisition_id,
          this.updForm.materialName,
          this.updForm.specification,
          this.updForm.unit,
          this.updForm.purchaseNum,
          this.updForm.actual_num,
          this.updForm.price,
          this.updForm.tax,
          this.updForm.remark
        ).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          selectById_good(this.selectValue).then((response) => {
            this.tableData = response.data
            this.loading = false
            this.itemKey = Math.random()
          })
          this.updForm.id = ''
          this.updForm.requisition_id = ''
          this.updForm.materialName = ''
          this.updForm.specification = ''
          this.updForm.unit = ''
          this.updForm.purchaseNum = ''
          this.updForm.actual_num = ''
          this.updForm.price = ''
          this.updForm.tax = ''
          this.updForm.remark = ''
        }).catch((error) => {
          console.log(error)
        })
      },
      handleDelete(index, row) {
        this.$confirm('此操作将删除物料信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          RemoveGood(this.tableData[index].id).then((response) => {
            this.$message.success(response.message)
            this.loading = true
            console.log(this.selectValue)
            selectById_good(this.selectValue).then((response) => {
              this.tableData = response.data
              this.loading = false
              this.itemKey = Math.random()
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 获取部门名称
      getDepartName() {
        selAccountDepart(this.account).then((response) => {
          this.department = response.data.departName
          console.log('部门信息：' + response.data.departName)
        })
      }
    }
  }
</script>

<style scoped>
  .addr {
    font-size: 10px;
    color: #b4b4b4;
  }
</style>
